package com.yangye.pigenerator.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.yangye.pigenerator.model.GenConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yangye
 * @date 2020/03/13
 */
public class GenUtil {

	private static final String BASE_PATH = System.getProperty("user.dir") + "\\src\\main\\java\\com\\yangye\\";

	private static Configuration cfg = null;

	static {
		cfg = new Configuration();
		cfg.setClassForTemplateLoading(GenUtil.class, "/template");
	}

	public static void genCode(String moduleName, List<GenConfig> configs) throws IOException, TemplateException {
		List<String> templateNames = GenUtil.getTemplateNames();
		for (GenConfig genConfig : configs) {
			String rootPath = BASE_PATH + moduleName + File.separator;
			String filePath = "";
			Template template = null;
			for (String templateName : templateNames) {
				if (StrUtil.equals(templateName, "service")) {
					filePath = rootPath + "service" + File.separator + genConfig.getClassName() + "Service.java";
					template = cfg.getTemplate("/service.ftl");
				}
				if (StrUtil.equals(templateName, "serviceImpl")) {
					filePath = rootPath + "service" + File.separator + File.separator + "impl"
							+ File.separator + genConfig.getClassName() + "ServiceImpl.java";
					template = cfg.getTemplate("/serviceImpl.ftl");
				}
				if (StrUtil.equals(templateName, "controller")) {
					filePath = rootPath + "controller" + File.separator + genConfig.getClassName() + "Controller.java";
					template = cfg.getTemplate("/controller.ftl");
				}
				File file = new File(filePath);
				FileUtil.touch(file);
				Writer out = new OutputStreamWriter(new FileOutputStream(file));
				Map<String, Object> params = BeanUtil.beanToMap(genConfig);
				params.put("moduleName", moduleName);
				template.process(params, out);
			}
		}
	}

	private static List<String> getTemplateNames() {
		List<String> templateNames = new ArrayList<>();
		templateNames.add("service");
		templateNames.add("serviceImpl");
		templateNames.add("controller");
		return templateNames;
	}
}
